import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {HttpClient} from '@angular/common/http';
import {NzMessageService} from 'ng-zorro-antd';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.scss']
})
export class ListComponent implements OnInit {
  list = [];
  loading = false;

  constructor(
    private router: Router,
    private http: HttpClient,
    private message: NzMessageService,
  ) {
  }

  ngOnInit() {
    this.loadData();
  }

  loadData() {
    this.loading = true;
    this.http.get<any[]>('/api/database').subscribe(res => {
      this.list = res;
      this.loading = false;
    });
  }

  add() {
    this.router.navigate(['/database/add']);
  }

  edit(id: any) {
    this.router.navigate(['/database/edit', id]);
  }

  copy(id: any) {
    this.http.get<any[]>('/api/database/copy/' + id).subscribe(() => {
      this.loadData();
      this.message.create('success', '复制成功');
    }, () => {
      this.message.create('error', `复制失败`);
    });
  }

  delete(id: any) {
    this.http.delete('/api/database/' + id).subscribe(() => {
      this.message.create('success', '删除成功');
      this.loadData();
    }, err => {
      this.message.create('error', `删除失败${err.error.message}`);
    });
  }
}
